/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.opgea.token.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.opgea.token.dao.EmployeeDAO;
import com.opgea.token.domain.entities.Employee;

/**
 * 
 * @author Ramesh
 */
@Repository
@Transactional
public class EmployeeDAOImpl implements EmployeeDAO {

    // private Session session =
    // HibernateUtil.getSessionFactory().openSession();
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public Employee create(Employee employee) {
	sessionFactory.openSession().save(employee);
	return employee;
    }

    @Override
    public Employee update(Employee employee) {
	Session session = sessionFactory.openSession();
	Transaction tx = session.getTransaction();
	tx.begin();
	Employee emp = (Employee) session.get(Employee.class, employee.getId());
	emp.setPrefix(employee.getPrefix());
	emp.setFirstName(employee.getFirstName());
	emp.setMiddleInitial(employee.getMiddleInitial());
	emp.setLastName(employee.getLastName());
	emp.setEmpCode(employee.getEmpCode());
	emp.setEmailId(employee.getEmailId());
	emp.setPhoneNo(employee.getPhoneNo());
	emp.setCompany(employee.getCompany());
	emp.setDestination(employee.getDestination());
	// emp.setLogin(employee.getLogin());
	tx.commit();
	return emp;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Employee> findAll() {
	List<Employee> employees = sessionFactory.openSession()
		.getNamedQuery("Employee.findAll").list();
	return employees;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Employee> findAllByCompanyId(Long companyId) {
	/*
	 * List<Employee> employees = sessionFactory.openSession()
	 * .getNamedQuery("Employee.findAllByCompanyId")
	 * .setParameter("companyId", companyId) .list();
	 */
	Session session = sessionFactory.openSession();
	Query query = session.createQuery("from Employee e WHERE e.company.id="
		+ companyId);
	List<Employee> employees = query.list();
	session.close();
	return employees;
    }

    @Override
    public Employee find(Long employeeId) {
	Employee employee = (Employee) sessionFactory.openSession().get(
		Employee.class, employeeId);
	return employee;
    }

    @Override
    public Employee delete(Long employeeId) {
	Employee employee = this.find(employeeId);
	sessionFactory.openSession().delete(employee);
	return employee;
    }

}
